package fan.project3_pksystem.Module;

import com.fasterxml.jackson.databind.ObjectMapper;
import fan.project3_pksystem.Game.GameRequest;
import fan.project3_pksystem.Game.GameResponse;
import fan.project3_pksystem.Mapper.UserMapper;
import fan.project3_pksystem.Project2PkSystemApplication;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;


@Slf4j
@Data
public class GameRoom {

    private String RoomId;
    private UserInfo user1;
    private UserInfo user2;
    private int[][] board = new int[15][15];
    private int winner = 0;
    private int lastPut = 0;
    private GameRoomManager gameRoomManager;
    private OnLinePlayers onLinePlayers;
    private int count = 0;

    GameRoom() {
        this.RoomId = UUID.randomUUID().toString();
        this.user1 = null;
        this.user2 = null;
        gameRoomManager = Project2PkSystemApplication.applicationContext.getBean(GameRoomManager.class);
        onLinePlayers = Project2PkSystemApplication.applicationContext.getBean(OnLinePlayers.class);
    }

    private void printBoard() {
        System.out.println(getRoomId() + "===============");
        for (int i = 0; i < 15; i++) {
            for (int j = 0; j < 15; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }
//    @Autowired
//    private GameRoomManager gameRoomManager;
//    @Autowired
//    private OnLinePlayers onLinePlayers;

    ObjectMapper objectMapper = new ObjectMapper();

    public void putChess(UserInfo userInfo, String Request) throws IOException {
//        System.out.println("================");
//        System.out.println(gameRoomManager);
//        System.out.println(onLinePlayers);
//        System.out.println(objectMapper);
        if (userInfo.getId() == lastPut) {
            System.out.println(userInfo.getUserName() + "试图重复落子,被判无效");
            return;

        }


        GameRequest gameRequest = objectMapper.readValue(Request, GameRequest.class);
//如果不是落子就不管了
        System.out.println(gameRequest);
        if (!Objects.equals(gameRequest.getMessage(), "putChess")) return;
//        拿到游戏房间
        GameRoom room;
        room = gameRoomManager.getRoomByUserId(userInfo.getId());
        if (room == null) return;

        int row = gameRequest.getRow();
        int col = gameRequest.getCol();

        if (board[row][col] == 0 && (lastPut == 0 || lastPut != gameRequest.getUserId())) {
            board[row][col] = gameRequest.getUserId() == user1.getId() ? 1 : 2;
            lastPut = gameRequest.getUserId();
            if (checkWinner(row, col)) winner = gameRequest.getUserId();
        } else return; //重复落子
//        printBoard();


        WebSocketSession session1 = onLinePlayers.getGameOl(room.getUser1().getId());
        WebSocketSession session2 = onLinePlayers.getGameOl(room.getUser2().getId());
        GameResponse gameResponse = new GameResponse();
        gameResponse.setCode("SUCCESS");
//        如果玩家掉线则判负
        if (session1 == null) {
            System.out.println("玩家一逃跑了");
            winner = room.getUser2().getId();

        }
        if (session2 == null) {
            System.out.println("玩家二逃跑了");
            winner = room.getUser1().getId();

        }
//        正常落子
        gameResponse.setCode("SUCCESS");
        gameResponse.setCol(col);
        gameResponse.setRow(row);
        gameResponse.setWinnerId(winner);
        gameResponse.setUserId(gameRequest.getUserId());
        gameResponse.setMessage("落子成功");
        String res = objectMapper.writeValueAsString(gameResponse);

        if (session1 != null) {
            session1.sendMessage(new TextMessage(res));
        }
        if (session2 != null) {
            session2.sendMessage(new TextMessage(res));
        }

        System.out.println("最终报文:" + res);
        lastPut = userInfo.getId();
        count++;
        if (count >= 15 * 15) {
            winner = -1;
        }

        if (winner != 0) {
            gameRoomManager.remove(this);

            try {
                if (winner != -1) {
                    UserMapper userMapper = Project2PkSystemApplication.applicationContext.getBean(UserMapper.class);
                    userMapper.winnerById(winner);
                    if(winner!=user1.getId()){
                        userMapper.loserById(user1.getId());
                    }else {
                        userMapper.loserById(user2.getId());
                    }
                }
            } catch (Exception e) {
                System.out.println("更新成绩时遇到异常");
            }
        }
    }


    //胜负判定
    private boolean checkWinner(int currentRow, int currentCol) {
        int left = currentCol, right = currentCol, target = board[currentRow][currentCol];
//        横向判断
        while (left - 1 >= 0 && board[currentRow][left - 1] == target) {
            left--;
        }
        while (right + 1 <= 14 && board[currentRow][right + 1] == target) {
            right++;
        }
        if (right - left + 1 >= 5) {
            return true;
        }
//竖向判断
        int up = currentRow, down = currentRow;
        while (up - 1 >= 0 && board[up - 1][currentCol] == target) {
            up--;
        }
        while (down + 1 <= 14 && board[down + 1][currentCol] == target) {
            down++;
        }
        if (down - up + 1 >= 5) {
            return true;
        }
//        左斜
        up = currentRow;
        down = currentRow;
        left = currentCol;
        right = currentCol;
        while (up - 1 >= 0 && left - 1 >= 0 && board[up - 1][left - 1] == target) {
            up--;
            left--;
        }
        while (down + 1 <= 14 && right + 1 <= 14 && board[down + 1][right + 1] == target) {
            down++;
            right++;
        }
        if ((down - up + 1) >= 5) {
            return true;
        }


//        右斜
        up = currentRow;
        down = currentRow;
        left = currentCol;
        right = currentCol;

        while (up - 1 >= 0 && left + 1 <= 14 && board[up - 1][left + 1] == target) {
            up--;
            left++;
        }
        while (down + 1 <= 14 && right - 1 >= 0 && board[down + 1][right - 1] == target) {
            down++;
            right--;
        }
        if ((down - up + 1) >= 5) {
            return true;
        }
        return false;
    }
}
